import java.util.Stack;

//法一：辅助栈
/*
class MinStack {

    Stack<Integer> xStack;
    Stack<Integer> minStack;

    */

/**
 * initialize your data structure here.
 *//*
    public MinStack() {
        xStack = new Stack<>();
        minStack = new Stack<>();
        minStack.push(Integer.MAX_VALUE);
    }

    public void push(int x) {
        xStack.push(x);
        minStack.push(Math.min(minStack.peek(), x));
    }

    public void pop() {
        xStack.pop();
        minStack.pop();
    }

    public int top() {
        return xStack.peek();
    }

    public int min() {
        return minStack.peek();
    }
}
*/

//法二：保存差值栈
class MinStack {
    Stack<Long> stack;
    Long min;

    /**
     * initialize your data structure here.
     */
    public MinStack() {
        stack = new Stack<>();
    }

    public void push(int x) {
        //如果栈为空，入0，否则入当前值和最小值的差值
        if (stack.isEmpty()) {
            stack.push(0L);
            min = (long) x;
        } else {
            stack.push((long) (x - min));
            min = Math.min(x, min);
        }
    }

    public void pop() {
        if (stack.peek() < 0) {
            //说明在栈顶的值是最小值，删除他需要改变最小值
            min = min - stack.pop();
            return;
        }
        stack.pop();
    }

    public int top() {
        if (stack.peek() > 0) {
            return Math.toIntExact(stack.peek() + min);
        } else {
            return Math.toIntExact(min);
        }
    }

    public int min() {
        return Math.toIntExact(min);
    }
}
